package com.ts.api.module.channel.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.entity.po.ChannelFlowConfigPO;
import com.ts.api.module.channel.entity.vo.RespChannelFlowConfigVO;
import com.ts.api.module.channel.service.ChannelConfigIpCityService;
import com.ts.api.module.channel.service.ChannelConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 渠道配置协议
 * 协议、流程及截留配置
 */
@RestController
@RequestMapping("/channel/config")
public class ChannelConfigController {

    @Autowired
    private ChannelConfigService channelConfigService;
    @Autowired
    private ChannelConfigIpCityService channelConfigIpCityService;

    /**
     *  获取渠道流程配置
     *  以及基本渠道基本信息
     *
     *  @return ResultVO
     */
    @GetMapping("/flow/get")
    public ResultVO<Object> getFlowConfig() {
       ChannelFlowConfigPO channelFlowConfigPO = channelConfigService.getFlowConfigByChannelId();
       if (channelFlowConfigPO == null) {
           BizException.fastFail(BizEnum.FLOW_CONFIG_EMPTY);
       }
        return ResultVO.suc(RespChannelFlowConfigVO.convertVO(channelFlowConfigPO));
    }

    /**
     *  根据IP定位城市是否选择留资-不需要令牌
     *
     *  @return ResultVO
     */
    @PostMapping("/get/ip/city/form")
    public ResultVO<Object> getIpCityForm(@RequestParamVo RequestVO requestVO) {
        String areaName = requestVO.get("areaName", String.class);
        String areaCode = requestVO.get("areaCode", String.class);
        if (!ValidParam.required(areaCode, areaName)) {
            return ResultVO.fail("非法参数");
        }

        Long channelId = ChannelContext.getId();
        //  查询是否该渠道允许此城市留资
        int hasExist = channelConfigIpCityService.countByAreaCode(channelId, areaCode);

        Map<String, Boolean> map = MapUtils.newHashMap(newMap -> newMap.put("hasExist", hasExist > 0));
        return ResultVO.suc(map);
    }
}
